<template>
    <div>
        <div v-if="!sys.appId">
            <div class="showcovertoast">
                <div class="showcovertitle">微信公众号</div>
                <div class="wxlogoimg">
                    <img class="el-upload-list__item-thumbnail" src="@/assets/img/wxlogo.png" alt="" />
                </div>
                <div class="footerbtn">
                    <a href="https://mp.weixin.qq.com/cgi-bin/wx?token=&lang=zh_CN" target="_blank"
                        style="color: var(--main-color); text-decoration: none">
                        <el-button class="btnstyle" round> 立即注册 </el-button>
                    </a>
                    <el-button class="btnstyle" type="primary" round @click="getAuthorizerQrcode">
                        立即授权
                    </el-button>
                </div>
            </div>
            <div class="footer-size">
                <p class="footer-size-one" style="color: var(--main-color)">注意:公众号主体必须是企业(包含个体工商户)</p>
                <p class="footer-size-two">将公众号授权给本系统，系统将会自动绑定您的微信公众号，您不需要做其它任何复杂操作，即可管理您的微信公众号平台。</p>
            </div>
        </div>
        <div class="weapp-info" v-else>
            <div class="weapp-message">
                <el-form :model="sys" label-width="140" style="margin-top: 20px">
                    <el-form-item label="公众号名称：">
                        <div class="iptbox" style="display: flex; align-items: center">
                            <h3 style="">{{ sys.nickName }}</h3>
                            <el-button style="margin-left: 10px" type="danger" size="small" plain round
                                @click="handleDelete">解绑公众号</el-button>
                            <el-button size="small" style="margin-left: 10px" round @click="redupAuthorizer">
                                重新授权
                            </el-button>
                        </div>
                    </el-form-item>
                    <el-form-item label="公众号简称：">
                        <div class="iptbox">
                            <p>{{ sys.nickName }}</p>
                        </div>
                    </el-form-item>
                    <el-form-item label="公众号头像：">
                        <div class="iptbox">
                            <img class="iptboximg" :src="sys.headImg" />
                        </div>
                    </el-form-item>
                    <el-form-item label="公众号介绍：">
                        <div class="iptbox">
                            <p>{{ sys.signature }}</p>
                        </div>
                    </el-form-item>
                    <el-form-item label="类型：">
                        <div class="iptbox">
                            <p>{{ sys.serviceType === 2 ? '服务号' : '订阅号' }}</p>
                        </div>
                    </el-form-item>
                    <el-form-item label="公众号AppID：">
                        <div class="iptbox">
                            <p>{{ sys.appId }}</p>
                        </div>
                    </el-form-item>
                    <!-- <el-form-item label="服务类目：">
                        <div class="iptbox">
                            <p>{{ sys.categories }}</p>
                        </div>
                    </el-form-item> -->
                    <el-form-item label="主体信息：">
                        <div class="iptbox">
                            <p>{{ sys.principalName }}</p>
                        </div>
                    </el-form-item>
                    <el-form-item label="微信认证：">
                        <div class="iptbox">
                            <p style="color: var(--main-color)">
                                {{ sys.verifyType === -1 ? '未认证' : '已认证' }}
                            </p>
                        </div>
                    </el-form-item>
                    <el-form-item label="公众号密钥配置：">
                        <div class="iptbox" @click="configure" style="display: flex; cursor: pointer;">
                            <p :style="{ color: sys.appSecretExist === '01' ? 'var(--main-color)' : '#ff4d4f' }">
                                {{ sys.appSecretExist === '01' ? '已配置' : '未配置' }}
                            </p>
                            <span style="margin-left: 10px;" v-if="sys.appSecretExist === '01'">修改</span>
                        </div>
                    </el-form-item>
                    <!-- 文件上传功能 -->
                    <el-form-item label="上传域名校验文件：">
                        <div style="display: flex;flex-direction: column;">
                            <div style="display: flex;">
                                <div v-if="sys.verificationFile" style="color:var(--main-color)">
                                    {{ sys.verificationFile }}
                                </div>
                                <el-upload class="upload-demo" :headers="fileHeaders" :before-upload="beforeFileUpload"
                                    :show-file-list="false" :action="uploadImageUrl" :on-success="successFileUpload">
                                    <el-button size="small" type="primary" style="margin-left: 5px;">
                                        {{ sys.verificationFile ? '修改' : '选择文件' }}
                                    </el-button>
                                </el-upload>
                            </div>
                            <div>
                                仅支持上传txt文件
                            </div>
                        </div>
                    </el-form-item>
                    <!-- <el-form-item label="更新时间：">
                        <span>{{ sys.versionUpdateTime }}</span>
                    </el-form-item> -->
                </el-form>
            </div>
            <div class="webapp-code">
                <p>微信 “扫一扫” 访问线上公众号</p>
                <img :src="sys.qrcodeUrl" referrerpolicy="no-referrer"
                    style="width: 140px; height: 140px; margin-top: 20px" />

                <div class="operation">
                    <!-- <a>线上版本号：{{ sys.releaseVersion }}</a>
                    <div class="line"></div> -->
                    <a download :href="sys.qrcodeUrl">下载公众号码</a>
                </div>

                <div class="desc">下载更多尺寸的公众号码可以到“微信公众号后台-设置-基本设置-公众号码”</div>

                <!-- <el-form :model="sys" class="versionText">
                    <el-form-item label="最新版本号：">
                        <span style="font-size: 16px">{{ sys.version }}</span>
                        <el-button size="small" class="btnstyle" round type="primary" @click="handleUpdateWeApp"
                            v-if="sys.version !== sys.releaseVersion" :icon="Top">
                            立即更新
                        </el-button>
                    </el-form-item>
                    <el-form-item label="审核状态：">
                        <div style="display: flex; align-items: center">
                            <p v-if="auditStatus == 0" style="color: var(--main-color); font-size: 16px">审核通过</p>
                            <p v-if="auditStatus == 1" style="color: #fd4e4e; font-size: 16px">审核失败</p>
                            <p v-if="auditStatus == 2" style="color: var(--main-color); font-size: 16px">审核中</p>
                            <el-button size="small" v-if="auditStatus == 2" class="btnstyle" round
                                @click="handleUnbind">
                                撤回审核
                            </el-button>
                        </div>

                        <el-button size="small" v-if="auditStatus == 1" class="btnstyle" round
                            @click="showReasonDialog = true">
                            查看失败原因
                        </el-button>
                    </el-form-item>
                </el-form> -->

                <div class="btn-list">
                    <!-- <div class="manage-btn" @click="getWeAppTrialQRCodeInfo(0)">查看体验码</div> -->
                    <div class="set-btn" @click="toDecoration">去装修</div>
                </div>
            </div>
        </div>

        <el-dialog v-model="showWeappCodeDialog" width="260" title="查看体验码" :close-on-click-modal="false">
            <div style="text-align: center">
                <img :src="weappQrCode" style="width: 200px; height: 200px" />
            </div>
        </el-dialog>

        <el-dialog v-model="showReasonDialog" width="360" title="审核失败原因" :close-on-click-modal="false">
            <div v-html="auditFailReason"></div>
        </el-dialog>

        <el-dialog v-model="showUpdateDialog" title="公众号更新" width="460" @close="handleClose"
            :close-on-click-modal="false">
            <div v-loading="auditLoading">
                <el-form :model="sys">
                    <el-form-item label="线上版本号：">
                        <el-tag type="info">{{ sys.releaseVersion }}</el-tag>
                    </el-form-item>
                    <el-form-item label="最新版本号：">
                        <el-tag type="primary">{{ sys.version }}</el-tag>
                    </el-form-item>
                    <el-form-item label="更新时间：">
                        <el-tag type="info">{{ sys.versionUpdateTime }}</el-tag>
                    </el-form-item>
                    <el-form-item label="体验码：">
                        <img :src="weappQrCode" style="width: 200px; height: 200px" />
                    </el-form-item>
                </el-form>
            </div>

            <template #footer>
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleAuditWeApp">提交审核</el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="configureDialog" :title="sys.appSecretExist === '01' ? '修改公众号密钥配置' : '配置公众号密钥'" width="460"
            :close-on-click-modal="false">
            <el-form :model="sys">
                <el-form-item label="公众号密钥：">
                    <el-input v-model="sys.appSecret" placeholder="请输入公众号密钥"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="submit">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {
    delBindGZH,
    getAppletAuthQr,
    getWeAppAuditStatus,
    getWeAppTrialQRCode,
    getGZHAuthorizerInfo,
    undoWeappAudit,
    weAppAudit,
    weAppUpdate,
    editConfigure,
    uploadTestFile
} from '@/api/ApiList'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Top } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import Success from '@/views/result/Success.vue'

const userStore = useUserStore()
let { accessToken } = userStore

// 上传路径
const uploadImageUrl = `${import.meta.env.VITE_API_URL}wp/uploadVerificationFile`
// 传递 token
const fileHeaders = { Authorization: 'Bearer ' + userStore.accessToken, store_id: localStorage.getItem('lty-store-id') }

const router = useRouter()
const configureDialog = ref(false)

const sys = reactive({
    id: '',
    nickName: '',
    headImg: '',
    signature: '',
    appId: '',
    categories: '',
    principalName: '',
    verifyType: -1,
    version: '',
    versionUpdateTime: '',
    releaseVersion: '',
    auditStatus: '',
    qrcodeUrl: '',
    serviceType: 0,
    appSecretExist: '',
    appSecret: '',
    verificationFile: ''
})

// 上传文件相关
const uploadedFileName = ref('')

// 前置校验
function beforeFileUpload(file: File) {
    const isTxt = file.type === 'text/plain' || /\.txt$/i.test(file.name)
    if (!isTxt) {
        ElMessage.error('只能上传txt文件类型！')
        return false
    }
    const maxBytes = 32
    if (file.size > maxBytes) {
        ElMessage.error(`文件大小不能超过${maxBytes}字节!`)
        return false
    }
    return true
}

function successFileUpload(file: any, response: any) {
    console.log(response, "response====");
    // 设定上传成功后的文件名展示
    if (response && response.response.code === '00000') {
        uploadedFileName.value = file.name
        ElMessage.success('上传成功')
        getData()
    } else {
        ElMessage.error(response.response.msg)
    }
}

const auditStatus = ref()
const weappQrCode = ref('')
const showWeappCodeDialog = ref(false)
const showUpdateDialog = ref(false)
const auditLoading = ref(false)
const auditFailReason = ref('')
const showReasonDialog = ref(false)

function redupAuthorizer() {
    ElMessageBox.confirm('确认或换绑其他公众号吗？', '重新授权公众号', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        getAuthorizerQrcode()
    })
}

async function getAuthorizerQrcode() {
    const res = await getAppletAuthQr()
    if (res.code === '00000') {
        window.open(res.msg)
    }
}

async function getWeAppStatus() {
    const res = await getWeAppAuditStatus({})
    if (res.code === '00000') {
        auditStatus.value = res.data.status
        auditFailReason.value = res.data.reason
    }
}

async function handleUpdateWeApp() {
    let loadingMessage: ReturnType<typeof ElMessage> | null = null
    loadingMessage = ElMessage({
        message: '正在更新，请稍后...',
        type: 'info',
        duration: 0,
        showClose: false
    })
    try {
        const res = await weAppUpdate({})
        if (res.code === '00000') {
            ElMessage.success('更新版本成功')
            getWeAppTrialQRCodeInfo(1)
            getData()
            showUpdateDialog.value = true
        }
    } catch (e) {
    } finally {
        loadingMessage.close()
    }
}

async function handleAuditWeApp() {
    try {
        auditLoading.value = true
        const res = await weAppAudit({})
        if (res.code === '00000') {
            ElMessage.success('提交审核成功')
            showUpdateDialog.value = false
            await getData()
        }
    } catch (e) {
    } finally {
        auditLoading.value = false
    }
}

async function getWeAppTrialQRCodeInfo(showDialog: number) {
    const res = await getWeAppTrialQRCode({})
    if (res.code === '00000') {
        weappQrCode.value = res.msg
        if (showDialog === 0) {
            showWeappCodeDialog.value = true
        }
    }
}

function handleDelete() {
    ElMessageBox.confirm(
        '确定解绑该公众号吗？解绑后公众号将会删除全部数据，请谨慎操作！',
        '解绑公众号',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        deleteWeappAuth()
    })
}

function handleClose() {
    showUpdateDialog.value = false
}

async function deleteWeappAuth() {
    const res = await delBindGZH({})
    if (res) {
        ElMessage.success('解绑成功')
        await getData()
    }
}

function handleUnbind() {
    ElMessageBox.confirm('确定撤回公众号审核吗？', '撤回审核', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        handleUndoWeapp()
    })
}

async function handleUndoWeapp() {
    const res = await undoWeappAudit({})
    if (res) {
        ElMessage.success('撤回审核成功')
        await getData()
    }
}

async function getData() {
    const res = await getGZHAuthorizerInfo({})
    if (res.code === '00000' && res.data) {
        sys.id = res.data.id
        sys.nickName = res.data.nickName
        sys.headImg = res.data.headImg
        sys.signature = res.data.signature
        sys.appId = res.data.appId
        sys.categories = res.data.categories
        sys.principalName = res.data.principalName
        sys.verifyType = res.data.verifyType
        sys.appSecretExist = res.data.appSecretExist
        sys.version = res.data.version
        sys.versionUpdateTime = res.data.versionUpdateTime
        sys.releaseVersion = res.data.releaseVersion
        sys.qrcodeUrl = res.data.qrcodeUrl
        sys.serviceType = res.data.serviceType
        sys.verificationFile = res.data.verificationFile
        // await getWeAppStatus()
    } else {
        sys.appId = ''
        // ElMessage.error(res.msg)
    }
}

const toDecoration = () => {
    router.push('/decoration/driving_school_decoration/weapp_diy')
}

const configure = () => {
    configureDialog.value = true
}

const cancel = () => {
    configureDialog.value = false
    sys.appSecret = ''
}

const submit = async () => {
    ElMessageBox.confirm('是否确认修改公众号密钥', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    })
        .then(async () => {
            const res = await editConfigure(sys.id, {
                appId: sys.appId,
                appSecret: sys.appSecret
            })
            if (res.code === '00000') {
                configureDialog.value = false
                ElMessage.success('修改成功')
                sys.appSecret = ''
                getData()
            }
        })
        .finally()
}

onMounted(() => {
    getData()
})
</script>

<style scoped lang="scss">
.page-content {
    width: 100%;

    .svg-icon {
        width: 1.8em;
        height: 1.8em;
        overflow: hidden;
        vertical-align: -8px;
        fill: currentcolor;
    }
}

.tag-item+.tag-item {
    margin-left: 5px;
}

.label {
    float: left;
    margin: 0.5rem 0 0.5rem 1.5rem;
    display: inline;
}

.labellist .label:nth-child(1) {
    margin-left: 0;
}

.bankcont_title_text {
    float: left;
    margin-right: 1rem;
    font-weight: bold;
}

.label_sonli {
    color: #5d87ff;
}

.tag-item {
    margin-left: 5px;
}

.tagcontsize {
    color: #999;
}

.tagcontbigsize {
    margin-top: 0.5rem;
}

.cartcont {
    margin-top: 0.2rem;
}

.tableimg {
    width: 100%;
    height: 100%;
}

.title_box_left {
    float: left;
    width: 4rem;
    height: 4rem;
    border-radius: 0.5rem;
    overflow: hidden;
    margin-right: 1rem;
}

.title_box_right {
    float: right;
    float: left;
}

.bankcont_title_text {
    height: 2rem;
    margin-top: 0.3rem;
}

.columnvideo {
    border-radius: 0.5rem;
}

.wxlogoimg {
    width: 260px;
    height: 220px;
}

.wxlogoimg img {
    width: 100%;
}

.showcovertoast {
    width: 14%;
    height: 440px;
    border-radius: 20px;
    box-shadow: 0 5px 20px 0 rgba(11, 3, 6, 0.1);
    margin-left: 43%;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    margin-top: 50px;
}

.footerbtn {
    width: 100%;
    display: flex;
    justify-content: center;
}

.btnstyle {
    margin-left: 20px;
}

.footerbtn .btnstyle:nth-child(1) {
    margin-left: 0px;
}

.showcovertitle {
    width: 100%;
    font-size: 20px;
    font-weight: bold;
    text-align: center;
    margin-top: 40px;
}

.footer-size {
    line-height: 32px;
    font-size: 14px;
}

.footer-size-one {
    display: block;
    width: 100%;
    text-align: center;
    margin-top: 40px;
}

.footer-size-two {
    display: block;
    width: 100%;
    text-align: center;
}

.iptbox {
    //width: 40%;
}

.iptbox .iptboxipt {
    //width: 70%;
}

.iptboximg {
    width: 60px;
    height: 60px;
    border-radius: 50%;
}

.weapp-info {
    display: flex;
    margin-top: 30px;

    .webapp-code {
        width: 360px;
        border-radius: 12px;
        box-shadow: 0 5px 20px 0 rgba(11, 3, 6, 0.1);
        padding-top: 20px;

        display: flex;
        flex-direction: column;
        //justify-content: space-around;
        align-items: center;

        .operation {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 20px;
            font-size: 14px;

            a {
                text-decoration: none;
                color: var(--el-color-primary);
            }

            .line {
                width: 1px;
                height: 10px;
                background-color: var(--el-color-primary);
                margin: 0 15px;
            }
        }

        .desc {
            padding: 0 20px;
            margin-top: 20px;
            font-size: 12px;
            margin-bottom: 50px;
            color: #888;
        }

        .versionText {
            :deep(.el-form-item__label) {
                font-size: 16px;
            }
        }

        .btn-list {
            display: flex;
            width: 100%;
            justify-content: center;
            margin-top: 30px;
            margin-bottom: 20px;

            .manage-btn {
                width: 120px;
                height: 40px;
                line-height: 40px;
                text-align: center;
                border-radius: 20px;
                border: 1px solid #ccc;
                margin-right: 15px;
                cursor: pointer;
            }

            .set-btn {
                width: 100px;
                height: 40px;
                line-height: 40px;
                text-align: center;
                border-radius: 20px;
                color: #fff;
                background: var(--el-color-primary);
                cursor: pointer;
            }
        }
    }

    .weapp-message {
        width: 460px;
        border-radius: 12px;
        box-shadow: 0 5px 20px 0 rgba(11, 3, 6, 0.1);
        padding: 10px;
        margin-right: 20px;
    }
}
</style>